
#include "fxcc/core/graph/opengl3/ImGuiGlfwApp.h"
#include "fxcc/core/graph/common/Geometry.h"
#include "fxcc/imgui/Editor.h"

#include "fxcc/core/graph/common/ImageMipmap.h"
#include "fxcc/core/graph/common/MSDF.h"
#include "fxcc/core/graph/common/MSDFResource.h"

#include "fxcc/core/graph/opengl3/Texture2DJack.h"
#include "fxcc/core/graph/opengl3/Texture2DArrayJack.h"
#include "fxcc/core/graph/opengl3/Texture3DJack.h"
#include "fxcc/core/graph/opengl3/TextureCubeArrayJack.h"
#include "fxcc/core/graph/opengl3/MeshJack.h"
#include "fxcc/core/graph/opengl3/IndexBuffer.h"
#include "fxcc/core/graph/opengl3/RenderTargetJack.h"

#include "fxcc/core/AssertManager.h"
#include "fxcc/bin/Serializer.h"
#include "fxcc/json/Serializer.h"

using namespace fxcc::platform;
using namespace fxcc::graph::common;
using namespace fxcc::graph::opengl3;
using namespace fxcc::imgui::graph::opengl3;
using BaseApp = fxcc::imgui::graph::opengl3::GlfwApp;

#undef main

extern "C" {
    __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
}

struct MSDFLoader
{
    static std::map<std::string, std::shared_ptr<fxcc::graph::common::MSDFResource>> m_MSDFResources;

    bool Load(const fxcc::Dir& dir)
    {
        for (const auto& childDir : dir.m_Dirs)
        {

            fs::path _mapPath = fs::path(childDir->m_RelativePath) / MSDFResource::DefaultAltasMap();
            fs::path _jsonPath = fs::path(childDir->m_RelativePath) / MSDFResource::DefaultAltasJson();

            fxcc::graph::common::MSDFResource::Desc desc;
            desc.m_AltasJsonPath = _jsonPath.string();
            desc.m_AltasMapPath = _mapPath.string();

            auto resource = std::make_shared<fxcc::graph::common::MSDFResource>(desc);

            m_MSDFResources[childDir->m_RelativePath] = resource;
        }

        return true;
    }
};

std::map<std::string, std::shared_ptr<fxcc::graph::common::MSDFResource>> MSDFLoader::m_MSDFResources;


struct MSDFEffect
{
    std::string m_FragMain;

    std::shared_ptr<fxcc::graph::opengl3::Shader> m_Shader;

    void Begin()
    {
        m_Shader->Use();
    }
    void End()
    {
        m_Shader->UnUse();
    }
    MSDFEffect(const std::string& fragMain)
        :m_FragMain(fragMain)
    {
        Init();

    }
    static std::string FragTemp()
    {
        std::string fragCodeTemp = R"(
{{{version}}}

{{{uniformPart}}}


in vec2 TexCoords;
in uint PageIndex;

out vec4 FragColor;

uniform float pxRange; 

uniform sampler2D msdf;

float median(float r, float g, float b) {
    return max(min(r, g), min(max(r, g), b));
}

float screenPxRange() {

    vec2 unitRange = vec2(pxRange)/vec2(textureSize(msdf, 0));
    vec2 screenTexSize = vec2(1.0)/fwidth(TexCoords);
    return max(0.5*dot(unitRange, screenTexSize), 1.0);


}

{{{fragMain}}}

void main()
{
    vec3 msd = texture(msdf, TexCoords).rgb;
    float sd = median(msd.r, msd.g, msd.b);
    float screenPxDistance = screenPxRange()*(sd - 0.5);
    float opacity = clamp(screenPxDistance + 0.5, 0.0, 1.0);
    
    if(opacity<.5f)
    {
        discard;
    }

    FragColor = Galculate_SDF(opacity);

}
)";
        return fragCodeTemp;
    }
    std::string GetFragCode() {

        const auto& buffer = fxcc::graph::opengl3::IBuffers::Inst();

        kainjow::mustache::mustache m1 = FragTemp();
        kainjow::mustache::data d1;
        d1.set("version", fxcc::graph::opengl3::IBuffers::GetVersionStr());
        d1.set("uniformPart", fxcc::graph::opengl3::IBuffers::GetUniformPart3d());
        d1.set("fragMain", m_FragMain);

        return m1.render(d1);
    }
    bool Init()
    {
        std::string vertCode = GetVertCode();
        std::string fragCode = GetFragCode();

        std::cout << fragCode << std::endl;

        m_Shader = std::make_shared<fxcc::graph::opengl3::Shader>(vertCode, fragCode);

        m_Shader->Use();
        m_Shader->setInt("msdf", 0);
        m_Shader->Bind("PassBuffer", 0);
        m_Shader->Bind("ObjBuffer", 1);
        //for (int i = 0; i < 8; i++)
        //{
        //    std::string label = std::string("msdf[") + std::to_string(i) + "]";
        //    m_Shader->setInt(label, i);
        //}
        return true;
    }

    std::string GetVertCode()
    {
        auto& buffers = fxcc::graph::opengl3::IBuffers::Inst();

        kainjow::mustache::mustache m1 = GetVertTemp();
        kainjow::mustache::data d1;
        d1.set("version", buffers.GetVersionStr());
        d1.set("uniformPart", buffers.GetUniformPart3d());

        return m1.render(d1);
    }
    std::string GetVertTemp()
    {
        return R"(

{{{version}}}

layout(location=0) in vec2 aPos;
layout(location=1) in vec2 aTexCoord;

{{{uniformPart}}}

out vec2 TexCoords;

void main()
{
    TexCoords= aTexCoord;
    gl_Position =passData.projView* objData.world*  vec4(aPos,0.0f,1.0f);
};
)";

    }

};
struct SimpleApp : public BaseApp
{
public:

    std::shared_ptr<ImageMipmap> m_ImageMipMap;

    std::shared_ptr< MSDFEffect> m_MSDFEffect;

    std::shared_ptr<MSDFResource> m_MSDFResource;

    glm::vec4 color;

    fxcc::graph::common::Camera camera;

    fxcc::graph::common::OrthoCamera camera2;

    float pxRange{ 4.0f };

    SimpleApp(const fxcc::platform::common::App::Desc& desc) : BaseApp(desc), color(1.0)
    {
    }
    void CreateText()
    {
        m_MSDFMesh = m_MSDFResource->CreateTextMesh(text, m_FontSize);
    }
    bool Init() override
    {
        if (!BaseApp::Init())
        {
            return false;
        }

        if (!InitResources())
        {
            return false;
        }

        return true;
    };

    MSDFLoader msdfLoader;
    std::string text = "Hello world my name is the orcx";

    bool InitResources()
    {
        ImageMipmap::MipMapData image(1024, 1024, 4, 2);
        fxcc::graph::opengl3::RenderTargetJack::Desc desc(1, image);

        camera.SetPosition(glm::vec3(5.0f));
        camera.LookAt(glm::vec3(0.0f));

        camera2.SetPosition(glm::vec3(0, 0, 10.0f));
        camera2.LookAt(glm::vec3(0.0f));


        auto& am = fxcc::AssertManager::Inst();

        {

            msdfLoader.Load(fxcc::AssertManager::GetAbsoluteFile("msdf"));
            m_MSDFResource = msdfLoader.m_MSDFResources.begin()->second;
            CreateText();

        }

        {
            const std::string fragCode = R"(
uniform vec4 bgColor;
uniform vec4 fgColor;


vec4 Galculate_SDF(float opacity)
{
    return mix( bgColor, fgColor, opacity);
};
)";
            m_MSDFEffect = std::make_shared<MSDFEffect>(fragCode);

        }

        return true;
    };

    fxcc::imgui::Editor editor;

 
    void OnEdit() override
    {
        ImGui::DockSpaceOverViewport(0, ImGui::GetMainViewport());

        ImGui::Begin("MSDF");

        editor.EditInst<fxcc::graph::common::Transform>("transform", transform);
        bool flag{ 0 };
        flag |= editor.EditInst<std::string>("text", text);
        flag |= editor.EditInst<int>("fontSize", m_FontSize);

        if (ImGui::BeginCombo("family", ""))
        {
            for (const auto& [key, value] : MSDFLoader::m_MSDFResources)
            {
                bool selectable = ImGui::Selectable(key.c_str());
                if (selectable)
                {
                    m_MSDFResource = value;
                    
                    flag |= selectable;
                }
            }
            ImGui::EndCombo();
        }
        if (flag)
        {
            ztclog::info("recreate text mesh ");
            CreateText();
        }
     
        ImGui::Image(m_MSDFResource->m_MSDFMap->GetTextureId(), { 200,200 });

        ImGui::End();

        ImGui::Begin("Framebuffer");
        editor.AddFrameBuffer(m_RTJack->m_Textures[0]->GetTextureId());
        ImGui::End();
    }
    fxcc::graph::common::Transform transform;
    std::shared_ptr<fxcc::graph::opengl3::RenderTargetJack> m_RTJack;
    int m_FontSize = 20;

    MSDFMesh m_MSDFMesh;

    void OnDestroy() override
    {

        BaseApp::OnDestroy();
    }
    void OnFrameRender() override
    {
        glViewport(0, 0, m_Desc.m_Size.x, m_Desc.m_Size.y);

        glClearColor(color.x, color.y, color.z, color.w);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        m_RTJack->Begin();
        m_RTJack->ClearColor(color);
        m_RTJack->ClearBuffer(1, 1);


        auto& buffers = fxcc::graph::opengl3::IBuffers::Inst();

        fxcc::graph::common::Effect3d::PassData passData;
        fxcc::graph::common::Effect3d::ObjData objData;

        passData.Load2(camera2);
        objData.Load(transform);
        buffers.SetPassData(passData);
        buffers.SetObjData(objData);


        m_MSDFEffect->Begin();
        m_MSDFResource->m_MSDFMap->SetShader(0);

        m_MSDFEffect->m_Shader->Use();
        m_MSDFEffect->m_Shader->setFloat("pxRange", pxRange);
        m_MSDFEffect->m_Shader->setVec4("bgColor", glm::vec4(1.f));
        m_MSDFEffect->m_Shader->setVec4("fgColor", glm::vec4(.0f));

        if (m_MSDFMesh.m_TextMesh)
        {
            m_MSDFMesh.m_TextMesh->Bind();
            m_MSDFMesh.m_TextMesh->DrawElementsAuto();
        }

        m_MSDFEffect->End();
        m_RTJack->End();
    };

    void OnFramebuffersize(int w, int h) override
    {
        BaseApp::OnFramebuffersize(w, h);
        camera.SetAspect(m_Desc.Aspect());
        camera2.SetHalfExtends(glm::vec3(w / 2.0f, h / 2.0f, 20.0f));

        fxcc::graph::opengl3::RenderTargetJack::Desc desc(1, { w, h, 3, 0 });
        m_RTJack = std::make_shared<fxcc::graph::opengl3::RenderTargetJack>(desc);


    }
    void OnUpdate() override
    {
        BaseApp::OnUpdate();

        float ctTime = m_GlfwlTimer.m_CurrentTime;
        float deltaTime = m_GlfwlTimer.m_DeltaTime;

        camera.FreeMove(m_Input, deltaTime);;


    }
};

int main()
{
    ztclog::pushFunction([](const ztclog::Line& line)
        {
            if (line.m_Type != ztclog::Line::Type::_line_debug_)
            {
                std::cout << line.m_Text << std::endl;
            } });

            using _App = SimpleApp;
            using _Desc = fxcc::platform::common::App::Desc;

            _Desc desc;
            desc.m_Pos = glm::ivec2(100, 100);
            desc.m_Size = glm::ivec2(900, 600);
            desc.m_ScaleFactor = 1.0f;

            desc.m_Title = "sdh render ";
            std::shared_ptr<_App> _app = std::make_shared<_App>(desc);
            return _app->Run();
};
